// pages/whereami/whereami.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isOpen: false,
    latitude: 0,
    longitude: 0,
    isMap: false
  },

  //内置地图上显示当前定位
  openloc: function () {
    var that = this
    wx.getLocation({
      success: function (res) {
        // console.log(res)
        wx.openLocation({
          latitude: res.latitude,
          longitude: res.longitude,
        })
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          isOpen: true
        })
      },
      fail: function (err) {
        console.error(err)
      }
    })
  },

  //选择附近的地图标记
  nearby: function (e) {
    var that = this
    this.mapCtx = wx.createMapContext('mymap')
    var latitude = this.data.latitude
    var longitude = this.data.longitude
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: function (res) {
        console.log(res)
        var r = that.getDistance(longitude,latitude,res.longitude,res.latitude)
        console.log(r)
        var info = "你选择了【"+res.name+"】\n"
        info += "位于【"+res.address+"】\n"
        info += "和你的直线距离大约【 "+Math.round(r)+" 】米"
        that.mapCtx.moveToLocation({
          latitude:res.latitude,
          longitude:res.longitude
        })
        that.setData({
          info:info,
          isMap: true
        })
      }
    })
  },

  /**
   * 获取两经纬度之间的距离
   * @param {number} e1 点1的东经, 单位:角度, 如果是西经则为负
   * @param {number} n1 点1的北纬, 单位:角度, 如果是南纬则为负
   * @param {number} e2
   * @param {number} n2
   */
  getDistance: function (e1, n1, e2, n2) {
    const R = 6378137.0 //地球半径，单位米
    const { sin, cos, asin, PI, hypot } = Math
    /** 根据经纬度获取点的坐标 */
    let getPoint = (e, n) => {
      e *= PI / 180
      n *= PI / 180
      //这里 R* 被去掉, 相当于先求单位圆上两点的距, 最后会再将这个距离放大 R 倍
      return { x: cos(n) * cos(e), y: cos(n) * sin(e), z: sin(n) }
    }
    let a = getPoint(e1, n1)
    let b = getPoint(e2, n2)
    let c = hypot(a.x - b.x, a.y - b.y, a.z - b.z)
    let r = asin(c / 2) * 2 * R
    return r
  },

})